package com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.login

import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.Spannable
import android.text.SpannableString
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.helasasa.maxfunds.lineofcredit.cashloan.ProjectApplication
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.http.hitPointCameroon
import com.helasasa.maxfunds.lineofcredit.cashloan.cameroon.screen.subview.HotlineCameroonDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityCameroonLoginBinding

class LoginCameroonActivity : AppCompatActivity() {

    private lateinit var loginViewModel: LoginCameroonViewModel
    private lateinit var binding: ActivityCameroonLoginBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 清空登录信息
        ProjectApplication.tkAction(isGet = false, "")
        ProjectApplication.uidAction(isGet = false, "")

        // 数据模型
        loginViewModel = ViewModelProvider(this)[LoginCameroonViewModel::class.java]

        // 关联布局
        binding = ActivityCameroonLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val hotline = binding.hotline
        val phone = binding.phone
        val submit = binding.submit
        val loading = binding.loading

        // 页面loading状态接口监听
        loginViewModel.loadingResult.observe(this@LoginCameroonActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                loading.visibility = View.GONE
            }
        })

        // 输入监听
        loginViewModel.loginFormState.observe(this@LoginCameroonActivity, Observer {
            val loginState = it ?: return@Observer

            submit.isEnabled = loginState.isDataValid
            if (loginState.isDataValid) {
                submit.setBackgroundResource(R.drawable.bg_blue_cor_12dp)
            } else {
                submit.setBackgroundResource(R.drawable.bg_blue_disable_cor_12dp)
            }
        })

        // 登录接口监听
        loginViewModel.loginResult.observe(this@LoginCameroonActivity, Observer {
            val loginResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (loginResult.error != null) {
                // TODO: 失败
                showMessage(loginResult.error)
            }
            if (loginResult.success != null) {
                // TODO: 成功
                loginViewModel.mainProcess()
            }
        })

        // 验证码接口监听
        loginViewModel.otpResult.observe(this@LoginCameroonActivity, Observer {
            val otpResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (otpResult.error != null) {
                // TODO: 失败
                showMessage(otpResult.error)
            }

            if (otpResult.directFlag == true) {
                // TODO: 直接登录
                loginViewModel.login()
            }

            if (otpResult.success == true) {
                // TODO: 输入otp
                val intent = Intent(this@LoginCameroonActivity, LoginCameroonOtpActivity::class.java)
                intent.putExtra("phone", loginViewModel.phone)
                intent.putExtra("directLoginFlag", loginViewModel.directLoginFlag)
                startActivity(intent)
            }
        })

        // 流程接口监听
        loginViewModel.mainProcessResult.observe(this@LoginCameroonActivity, Observer {
            val mainProcessResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (mainProcessResult.error != null) {
                showMessage(mainProcessResult.error)
            }

            if (mainProcessResult.success != null) {
                loginViewModel.nextRouter(mainProcessResult.success)
            }
        })

        // 页面需要跳转监听
        loginViewModel.nextRouterResult.observe(this@LoginCameroonActivity, Observer {
            val nextRouterResult = it ?: return@Observer

            loading.visibility = View.GONE
            startNextActivity(nextRouterResult.nextPage)
        })

        // 手机号输入监听
        phone.afterTextChanged {
            loginViewModel.loginPhoneDataChanged(phone.text.toString())
        }

        // 点击登录/注册
        submit.setOnClickListener {
            loading.visibility = View.VISIBLE
            hitPointCameroon("LOGIN_COMMIT")
            loginViewModel.startLogin(phone.text.toString())
        }

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineCameroonDialog().showNow(supportFragmentManager, "hotline")
            hitPointCameroon("SHOW_HOTLINE")
        }

        // 区号
        binding.phoneCode.text = ProjectApplication.mPhoneCode
        updateSpanText()
    }

    private fun startNextActivity(
        activity: Class<out AppCompatActivity>? = null,
        params: HashMap<String, String> = HashMap()
    ) {
        val nextActivity = activity ?: return
        try {
            val intent = Intent(this, nextActivity)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
            params.keys.forEach { gKey ->
                intent.putExtra(gKey, params[gKey])
            }
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onResume() {
        super.onResume()
        hitPointCameroon(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPointCameroon(type = this::class.java.simpleName, isPageEnd = true)
    }

    fun showMessage(message: String) {
        Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
    }

    private fun updateSpanText() {
        val text = binding.agreement.text.toString()
        val words = "Terms & Conditions privacy policy"
        val gStart = text.indexOf(words)
        if (gStart >= 0) {
            val gEnd = gStart + words.length
            val spanString = SpannableString(text)
            spanString.setSpan(
                ForegroundColorSpan(Color.parseColor("#FF8378")),
                gStart,
                gEnd,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )

            binding.agreement.text = spanString

            binding.agreement.setOnClickListener {
                val intent =
                    Intent(Intent.ACTION_VIEW, Uri.parse(ProjectApplication.mPrivacyPolicy)).apply {
                        flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    }
                if (intent.resolveActivity(ProjectApplication.instance.packageManager) != null) {
                    ProjectApplication.instance.startActivity(intent)
                } else {
                    ProjectApplication.instance.startActivity(
                        Intent.createChooser(intent, "Please select a browser to open")
                    )
                }
            }
        }
    }
}


fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(editable: Editable?) {
            afterTextChanged.invoke(editable.toString())
        }

        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
    })
}